package cn.signalpha.modules.shop.controller.api;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.signalpha.common.annotation.FormRepeatCommitAnnotation;
import cn.signalpha.common.cache.ConfigCache;
import cn.signalpha.common.cache.ConfigKeys;
import cn.signalpha.common.constant.AppConstant;
import cn.signalpha.common.constant.MsgConstant;
import cn.signalpha.common.dto.ConfigDTO;
import cn.signalpha.common.dto.IdDTO;
import cn.signalpha.common.utils.Arith;
import cn.signalpha.common.utils.Assert;
import cn.signalpha.core.boot.ctrl.BaseController;
import cn.signalpha.core.log.exception.ServiceException;
import cn.signalpha.core.mp.support.Condition;
import cn.signalpha.core.mp.support.Query;
import cn.signalpha.core.secure.TokenUser;
import cn.signalpha.core.tool.api.R;
import cn.signalpha.core.tool.jackson.JsonUtil;
import cn.signalpha.core.tool.support.Kv;
import cn.signalpha.core.tool.utils.BeanUtil;
import cn.signalpha.core.tool.utils.CollectionUtil;
import cn.signalpha.core.tool.utils.Func;
import cn.signalpha.core.tool.utils.ObjectUtil;
import cn.signalpha.modules.queue.enums.RedisDelayQueueEnum;
import cn.signalpha.modules.queue.utils.RedisDelayQueueUtil;
import cn.signalpha.modules.shop.dto.OrderConfirmDTO;
import cn.signalpha.modules.shop.dto.OrderDTO;
import cn.signalpha.modules.shop.entity.*;
import cn.signalpha.modules.shop.entity.enums.CouponUseTypeEnum;
import cn.signalpha.modules.shop.entity.enums.OrderStatusEnum;
import cn.signalpha.modules.shop.event.OrderConfirmEvent;
import cn.signalpha.modules.shop.service.*;
import cn.signalpha.modules.shop.vo.*;
import cn.signalpha.modules.shop.wrapper.OrderWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.core.IBaseClient;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.request.QueryTrackReq;
import com.kuaidi100.sdk.utils.SignUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


/**
 * 订单
 *
 * @author suguangjun
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_SHOP_NAME + "/wap/order")
@Api(value = "订单", tags = "订单")
public class ApiOrderController extends BaseController {

	private final CartService cartService;
	private final OrderService orderService;
	private final SellerService sellerService;
	private final LogisticsService logisticsService;
	private final CouponUserService couponUserService;
	private final OrderRefundService orderRefundService;
	private final OrderDetailService orderDetailService;
	private final ApplicationContext applicationContext;
	private final UserAddressService userAddressService;
	private final SellerVerifyService sellerVerifyService;
	private final RedisDelayQueueUtil redisDelayQueueUtil;
	private final GoodsCommentService goodsCommentService;
	private final OrderLogisticsService orderLogisticsService;

    @PostMapping("/confirm")
	@ApiOperationSupport(order = 1)
    @ApiOperation(value = "预生成订单", notes = "购物车提交传入cartIds，直接购物传入orderItem，用户更换地址或者修改商品数量时，重新调用这个接口，传入新的地址id")
    public R<OrderConfirmVO> confirm(@Valid @RequestBody OrderConfirmDTO orderConfirmDTO, TokenUser tokenUser){
        OrderConfirmVO orderConfirmVO = new OrderConfirmVO();
        orderConfirmVO.setUserAddress(userAddressService.getByUserId(orderConfirmDTO.getAddrId(), tokenUser.getUserId()));

        //组装用户提交的购物车商品项
        List<OrderConfirmVO.SellerCartItemVO> sellerCartItemList = cartService.getSellerCartItemList(orderConfirmDTO.getOrderItem(), orderConfirmDTO.getCartIds(), tokenUser.getUserId());
        if (CollectionUtil.isEmpty(sellerCartItemList)) {
            throw new ServiceException("请选择您需要的商品");
        }

        //根据商户组装购物车中的商品信息，返回每个商户的购物车商品信息
        List<CartVO> cartList = cartService.getShopCarts(sellerCartItemList);

        // 所有商户的订单信息
        int goodsNumTotal = 0;
		double orderPriceTotal = 0.0, goodsPriceTotal = 0.0, transportFee = 0.0;
		double deductMoney = 0.0, deductIntegral = 0.0, deductIntegralMoney = 0.0, deductCouponSeller = 0.0, deductPublicity = 0d;;
		List<Map<String, Object>> deductPublicityDetail = new ArrayList<>();
		List<OrderConfirmVO.SellerCartVO> sellerCartList = new ArrayList<>();
		for (CartVO cart : cartList) {
			OrderConfirmVO.SellerCartVO sellerCart = Objects.requireNonNull(BeanUtil.copy(cart, OrderConfirmVO.SellerCartVO.class));
			sellerCart.setSellerCartItemList(cart.getShopCartItems());
            applicationContext.publishEvent(new OrderConfirmEvent(orderConfirmDTO, sellerCart, tokenUser.getUserId()));
			goodsNumTotal = goodsNumTotal + sellerCart.getGoodsNumTotal();
			goodsPriceTotal = Arith.add(goodsPriceTotal, sellerCart.getGoodsPriceTotal());
			orderPriceTotal = Arith.add(orderPriceTotal, sellerCart.getOrderPriceTotal());
			transportFee =  Arith.add(transportFee, sellerCart.getTransportFee());
			deductMoney = Arith.add(deductMoney, sellerCart.getDeductMoney());
			deductCouponSeller = Arith.add(deductCouponSeller, sellerCart.getDeductCouponSeller());
			deductIntegral = Arith.add(deductIntegral, sellerCart.getDeductIntegral());
			deductIntegralMoney = Arith.add(deductIntegralMoney, sellerCart.getDeductIntegralMoney());
			deductPublicity = Arith.add(deductPublicity, sellerCart.getDeductPublicity());
			deductPublicityDetail.addAll(sellerCart.getDeductPublicityDetail());
            sellerCartList.add(sellerCart);
        }

		//此处处理全平台优惠券
		List<OrderConfirmVO.CouponVO> couponList = new ArrayList<>();
		List<OrderConfirmVO.CouponVO> couponNotList = new ArrayList<>();
		couponSystemConfirmOrderEvent(tokenUser.getUserId(), couponList, couponNotList, sellerCartList, orderConfirmDTO.getCouponId());
		double deductCouponSystem = Arith.round(sellerCartList.stream().mapToDouble(OrderConfirmVO.SellerCartVO::getDeductCouponSystem).sum()).doubleValue();
		if(deductCouponSystem > 0){
			orderPriceTotal = Arith.sub(orderPriceTotal, deductCouponSystem);
		}

		orderConfirmVO.setDeductMoney(deductMoney);
		orderConfirmVO.setDeductIntegral(deductIntegral);
		orderConfirmVO.setDeductIntegralMoney(deductIntegralMoney);
		orderConfirmVO.setDeductCouponSeller(deductCouponSeller);
		orderConfirmVO.setDeductCouponSystem(deductCouponSystem);
		orderConfirmVO.setDeductPublicity(deductPublicity);
		orderConfirmVO.setDeductPublicityDetail(deductPublicityDetail);
		orderConfirmVO.setTransportFee(transportFee);
		orderConfirmVO.setOrderPriceTotal(orderPriceTotal < 0 ? 0 : orderPriceTotal);
		orderConfirmVO.setGoodsPriceTotal(goodsPriceTotal);
		orderConfirmVO.setGoodsNumTotal(goodsNumTotal);
		orderConfirmVO.setSellerCartList(sellerCartList);
		orderConfirmVO.setCouponsList(couponList);
		orderConfirmVO.setCouponNotList(couponNotList);
        return R.data(orderService.putOrderConfirmCache(tokenUser.getUserId(), orderConfirmVO));
    }

	/**
	 * 平台优惠券处理，暂时只做一个类型
	 */
	private void couponSystemConfirmOrderEvent(Long userId, List<OrderConfirmVO.CouponVO> couponList, List<OrderConfirmVO.CouponVO> couponNotList, List<OrderConfirmVO.SellerCartVO> sellerCartList, Long couponId) {
		//这层过滤跟营销活动互斥的商品
		double orderPriceTotalJoin = 0d;
		List<Long> goodsIds = new ArrayList<>();
		for(OrderConfirmVO.SellerCartVO sellerCartVO : sellerCartList){
			for(OrderConfirmVO.SellerCartItemVO sellerCartItemVO : sellerCartVO.getSellerCartItemList()){
				if(sellerCartItemVO.getDeductPublicityIsCoupon() == 1){
					goodsIds.add(sellerCartItemVO.getGoodsId());
					orderPriceTotalJoin = Arith.add(orderPriceTotalJoin, sellerCartItemVO.getOrderPrice());
				}
			}
		}
		if(orderPriceTotalJoin <= 0){
			return;
		}
		double finalGoodsPriceTotal = orderPriceTotalJoin;
		couponUserService.listByUserIdAndSellerId(userId, 0L).forEach(couponUser -> {
			OrderConfirmVO.CouponVO couponVO = Objects.requireNonNull(BeanUtil.copy(couponUser, OrderConfirmVO.CouponVO.class));
			couponVO.setIsSelect(0);
			if(couponUser.getUseType().equals(CouponUseTypeEnum.COMMON.getType())){
				if(goodsIds.size() == 0){
					couponVO.setRemark("结算商品参与的活动不可与优惠券共享");
					couponNotList.add(couponVO);
				}else{
					if(finalGoodsPriceTotal >= couponUser.getMinPrice()){
						couponVO.setTargetKey(Func.join(goodsIds));
						couponList.add(couponVO);
					}else{
						couponVO.setRemark("商品未达到最消费金额");
						couponNotList.add(couponVO);
					}
				}
			}
		});

		couponList.sort((u1, u2) -> u2.getMoney().compareTo(u1.getMoney()));
		couponNotList.sort((u1, u2) -> u2.getMoney().compareTo(u1.getMoney()));
		if(CollectionUtil.isEmpty(couponList)){
			return;
		}

		if(CollectionUtil.isNotEmpty(couponList)){
			//抵扣优惠券，0不使用，null默认一张
			OrderConfirmVO.CouponVO selectCouponVO = null;
			if(couponId != null){
				if(couponId > 0){
					for (OrderConfirmVO.CouponVO couponVO : couponList) {
						if(couponVO.getId().equals(couponId)){
							couponVO.setIsSelect(1);
							selectCouponVO = couponVO;
						}
					}
				}
			}else {
				//自动选择金额最高的一张
				couponList.get(0).setIsSelect(1);
				selectCouponVO = couponList.get(0);
			}
			if(selectCouponVO != null){
				//牵扯到的商品和金额
				List<OrderConfirmVO.SellerCartItemVO> sellerCartItemList = new ArrayList<>();
				AtomicReference<Double> orderPriceTotal = new AtomicReference<>(0d);
				sellerCartList.forEach(sellerCartVO -> sellerCartVO.getSellerCartItemList().forEach(sellerCartItemVO -> {
					if(goodsIds.contains(sellerCartItemVO.getGoodsId()) && sellerCartItemVO.getOrderPrice() > 0){
						sellerCartItemList.add(sellerCartItemVO);
						orderPriceTotal.set(Arith.add(orderPriceTotal.get(), sellerCartItemVO.getOrderPrice()));
					}
				}));

				//优惠券金额
				double deductCoupon = selectCouponVO.getMoney();
				//实际可以抵扣
				double deductCouponMoney = Math.min(orderPriceTotal.get(), deductCoupon);
				//明细抵扣金额累计
				double itemDeductCouponMoneyTotal = 0d;
				//计算抵扣的权重
				for(OrderConfirmVO.SellerCartItemVO sellerCartItemVO : sellerCartItemList){
					//最后一个元素需要直接做减法
					double itemDeductCouponMoney, itemOrderPrice;
					double itemWight = Arith.div(sellerCartItemVO.getOrderPrice(), orderPriceTotal.get(), 5);
					if(sellerCartItemList.size() - 1 == sellerCartItemList.indexOf(sellerCartItemVO)){
						itemDeductCouponMoney = Arith.round(Arith.sub(deductCouponMoney, itemDeductCouponMoneyTotal)).doubleValue();
					}else {
						itemDeductCouponMoney = Arith.round(Arith.mul(deductCouponMoney, itemWight)).doubleValue();
					}
					itemOrderPrice = Arith.sub(sellerCartItemVO.getOrderPrice(), itemDeductCouponMoney);
					itemDeductCouponMoneyTotal = Arith.add(itemDeductCouponMoneyTotal, itemDeductCouponMoney);
					sellerCartItemVO.setOrderPrice(itemOrderPrice);
					sellerCartItemVO.setDeductCouponSystem(itemDeductCouponMoney);
				}

				//重新计算店铺的价格
				sellerCartList.forEach(sellerCartVO -> {
					double sellerCartDeductCouponSystem = Arith.round(sellerCartVO.getSellerCartItemList()
						.stream().mapToDouble(OrderConfirmVO.SellerCartItemVO::getDeductCouponSystem).sum()).doubleValue();
					sellerCartVO.setDeductCouponSystem(sellerCartDeductCouponSystem);
					sellerCartVO.setOrderPriceTotal(Arith.sub(sellerCartVO.getOrderPriceTotal(), sellerCartDeductCouponSystem));
				});
			}
		}
	}

	@PostMapping("/submit")
	@FormRepeatCommitAnnotation
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "提交订单", notes = "返回支付流水号，用户开始进行支付")
	public R<OrderNumbersVO> submit(@RequestBody OrderDTO.OrderSubmitDTO orderSubmitDTO, TokenUser tokenUser){
		OrderConfirmVO mergerOrder = orderService.getOrderConfirmCache(tokenUser.getUserId());
		if (mergerOrder == null) {throw new ServiceException("订单已过期，请重新下单");}

		// 设置备注
		if (CollectionUtil.isNotEmpty(orderSubmitDTO.getOrderShopList())) {
			mergerOrder.getSellerCartList().forEach(shopCartOrder -> orderSubmitDTO.getOrderShopList().forEach(item -> {
				if(Objects.equals(shopCartOrder.getSellerId(), item.getSellerId())){
					shopCartOrder.setRemarks(item.getRemarks());
					shopCartOrder.setSellerAddressId(item.getSellerAddressId());
					shopCartOrder.setDeliveryDate(item.getDeliveryDate());
					shopCartOrder.setDeliveryBeginTime(item.getDeliveryBeginTime());
					shopCartOrder.setDeliveryEndTime(item.getDeliveryEndTime());
				}
			}));
		}

		List<Order> orders = orderService.submitOrder(tokenUser.getUserId(), mergerOrder);
		String orderNo = Func.join(orders.stream().map(Order::getOrderNo).collect(Collectors.toList()));
		orderService.removeOrderConfirmCache(tokenUser.getUserId());

		ConfigDTO.ShopDTO config = ConfigCache.getObject(ConfigKeys.SHOP, ConfigDTO.ShopDTO.class);
		orders.forEach(order -> redisDelayQueueUtil.addDelayQueue(order.getId().toString(), config.getClose() * 60, RedisDelayQueueEnum.ORDER_CANCEL.getCode()));
		cartService.removeByIds(mergerOrder.getSellerCartList().stream().flatMap(i -> i.getSellerCartItemList().stream()).map(OrderConfirmVO.SellerCartItemVO::getId).collect(Collectors.toList()));
		return R.data(OrderNumbersVO.builder().orderNo(orderNo).orderType(orders.get(0).getOrderType()).build());
	}

	@GetMapping("/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name="orderType", dataType = "string", value = "订单类型"),
		@ApiImplicitParam(name="orderStatus", dataType = "string", value = "订单状态"),
		@ApiImplicitParam(name="logisticsType", dataType = "string", value = "物流方式"),
	})
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "订单分页", notes = "")
	public R<IPage<OrderVO>> page(@ApiIgnore @RequestParam Map<String, Object> params, Query query) {
		params.put("userId", getUser().getUserId());
		QueryWrapper<Order> wrapper = orderService.selectOrderWrapper(params);
		IPage<Order> page = orderService.page(Condition.getPage(query), wrapper);
		return R.data(OrderWrapper.build().pageVO(page));
	}

	@GetMapping("/count")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "订单角标", notes = "")
	public R<OrderVO.CountVO> count(TokenUser tokenUser) {
		OrderVO.CountVO countVO = new OrderVO.CountVO();
		countVO.setCount1(orderService.countByParams(Kv.create().set("userId", tokenUser.getUserId()).set("orderStatus", 0)));
		countVO.setCount2(orderService.countByParams(Kv.create().set("userId", tokenUser.getUserId()).set("orderStatus", 1)));
		countVO.setCount3(orderService.countByParams(Kv.create().set("userId", tokenUser.getUserId()).set("orderStatus", 2)));
		countVO.setCount4(orderService.countByParams(Kv.create().set("userId", tokenUser.getUserId()).set("orderStatus", 3).set("commentStatus", 0)));
		countVO.setCount5(orderRefundService.countByParams(Kv.create().set("userId", tokenUser.getUserId()).set("refundStatus", 0)));
		return R.data(countVO);
	}

	@GetMapping("/info")
	@ApiOperationSupport(order = 15)
	@ApiOperation(value = "订单详情", notes = "传入订单id")
	public R<OrderVO> info(@RequestParam String id) {
		return R.data(OrderWrapper.build().entityVO(orderService.getById(id)));
	}

	@PostMapping("/cancel")
	@ApiOperationSupport(order = 20)
	@ApiOperation(value = "订单取消", notes = "")
	public R cancel(@Valid @RequestBody IdDTO idDTO) {
		return R.status(orderService.cancelOrder(idDTO.getId(), getUser().getUserId()));
	}

	@PostMapping("/update/address")
	@ApiOperationSupport(order = 21)
	@ApiOperation(value = "修改地址", notes = "")
	public R updateAddress(@Valid @RequestBody OrderDTO.UpdateUserAddressDTO orderDTO) {
		return R.status(orderService.updateUserAddress(orderDTO.getId(), orderDTO.getAddressId()));
	}

	@PostMapping("/receipt")
	@ApiOperationSupport(order = 21)
	@ApiOperation(value = "确认收货", notes = "")
	public R receipt(@Valid @RequestBody IdDTO idDTO) {
		Long userId = getUser().getUserId();
		Order order = orderService.getById(idDTO.getId());
		Assert.isNull(order, MsgConstant.OBJECT_NULL);
		Assert.isTrue(order.getUserId().equals(userId), MsgConstant.UNAUTHORIZED);
		Assert.isTrue(order.getOrderStatus().equals(OrderStatusEnum.SEND_OUT.getStatus()), "当前订单状态不可进行确认收货");
		return R.data(orderService.receiptOrder(idDTO.getId()));
	}

	@PostMapping("/verify")
	@ApiOperationSupport(order = 23)
	@ApiOperation(value = "核销订单", notes = "核销")
	public R finish(@Valid @RequestBody IdDTO idDTO){
		Long userId = getUser().getUserId();
		Order order = orderService.getById(idDTO.getId());
		Assert.isNull(order, MsgConstant.OBJECT_NULL);
		Assert.isTrue(order.getOrderStatus().equals(OrderStatusEnum.SEND_OUT.getStatus()), "当前订单状态不可进行核销");

		boolean verifyPermission = false;
		ConfigDTO.VerifyUserDTO config = ConfigCache.getObject(ConfigKeys.VERIFY_USER, ConfigDTO.VerifyUserDTO.class);
		if(CollectionUtil.isNotEmpty(config.getList()) && config.getList().stream().anyMatch(i -> i.getId().equals(userId))){
			verifyPermission = true;
		}
		if(!verifyPermission){
			if(sellerVerifyService.countBySellerIdAndUserId(order.getSellerId(), userId) > 0){
				//是商家的核销员，还要判断是不是这个店铺的核销员
				Seller seller = sellerService.getBaseById(order.getSellerId());
				SellerAddress orderAddress = JsonUtil.parse(order.getLogisticsSellerInfo(), SellerAddress.class);
				Assert.isNull(orderAddress, "订单未携带自提点信息，核销失败");
				List<SellerPickConfigVO> sellerPickConfigList = JsonUtil.parseArray(seller.getPickConfig(), SellerPickConfigVO.class);
				Optional<SellerPickConfigVO> sellerPickConfigOptional = sellerPickConfigList.stream().filter(pickConfigVO -> pickConfigVO.getAddressId().equals(orderAddress.getId())).findFirst();
				if(!sellerPickConfigOptional.isPresent()){
					throw new ServiceException("订单携带的自提点已被商家从配置中移除，请联系商家处理");
				}
				SellerPickConfigVO sellerPickConfig = sellerPickConfigOptional.get();
				if(sellerPickConfig.getVerifyId().contains(userId.toString())){
					verifyPermission = true;
				}
			}
		}
		if(!verifyPermission){
			Seller seller = sellerService.getBaseById(order.getSellerId());
			if(seller.getUserId().equals(userId)){
				verifyPermission = true;
			}
		}
		if(!verifyPermission){
			throw new ServiceException("当前账号无核销权限");
		}
		orderService.receiptOrder(idDTO.getId());
		return R.data(OrderWrapper.build().entityVO(orderService.getById(idDTO.getId())));
	}

	@PostMapping("/comment")
	@ApiOperationSupport(order = 30)
	@ApiOperation(value = "订单评价", notes = "")
	public R comment(@Valid @RequestBody OrderDTO.CommentDTO commentDTO) {
		return R.status(orderService.commentOrder(commentDTO, getUser().getUserId()));
	}

	@GetMapping("/comment/list")
	@ApiOperationSupport(order = 31)
	@ApiOperation(value = "订单评价列表", notes = "")
	public R<List<GoodsComment>> commentList(@RequestParam String id) {
		Order order = orderService.getById(id);
		Assert.isNull(order, MsgConstant.OBJECT_NULL);
		List<OrderDetail> orderDetailList = orderDetailService.listByOrderNo(order.getOrderNo());
		List<Long> goodsIds = orderDetailList.stream().map(OrderDetail::getGoodsId).collect(Collectors.toList());
		List<GoodsComment> list = goodsCommentService.list(Wrappers.<GoodsComment>query().lambda()
			.eq(GoodsComment::getUserId, getUser().getUserId())
			.in(GoodsComment::getGoodsId, goodsIds).eq(GoodsComment::getIsShow, 1)
		);
		return R.data(list);
	}

	@SneakyThrows
	@GetMapping("/track")
	@ApiOperationSupport(order = 50)
	@ApiOperation(value = "订单物流", notes = "传入订单物流信息的id")
	public R track(@RequestParam String id) {
		OrderLogistics orderLogistics = orderLogisticsService.getById(id);
		Assert.isNull(orderLogistics, MsgConstant.OBJECT_NULL);
		Order order = orderService.getByOrderNo(orderLogistics.getOrderNo());
		Assert.isNull(order, "物流单的订单不存在");
		Logistics logistics = logisticsService.getById(orderLogistics.getLogisticsId());
		UserAddress userAddress = JsonUtil.parse(order.getLogisticsInfo(), UserAddress.class);
		QueryTrackReq queryTrackReq = new QueryTrackReq();
		QueryTrackParam queryTrackParam = new QueryTrackParam();
		queryTrackParam.setCom(logistics.getCode());
		queryTrackParam.setNum(orderLogistics.getLogisticsNo());
		queryTrackParam.setPhone(userAddress.getMobile());
		queryTrackParam.setResultv2("1");
		String param = new Gson().toJson(queryTrackParam);

		queryTrackReq.setParam(param);
		queryTrackReq.setCustomer("0739233AFCD0B4C7B44CE3F4E7390C65");
		queryTrackReq.setSign(SignUtils.querySign(param ,"NnXnEXNU2565", "0739233AFCD0B4C7B44CE3F4E7390C65"));

		IBaseClient baseClient = new QueryTrack();
		return R.data(baseClient.execute(queryTrackReq));
	}

	@PostMapping("/delivery/notice")
	@ApiOperationSupport(order = 100)
	@ApiOperation(value = "同城配送回调通知", notes = "前端不需要调")
	public R deliveryNotice(@RequestBody Map<String, Object> paramsMap) {
		log.info("同城配送回调参数：{}", paramsMap);
		Map<String, Object> dataMap = (Map<String, Object>) paramsMap.get("data");
		String orderNo = MapUtil.getStr(dataMap, "order_no");
		Order order = orderService.getByOrderNo(orderNo);
		if(ObjectUtil.isNotEmpty(order)){
			OrderDeliveryVO orderDeliveryVO = JsonUtil.parse(order.getLogisticsDeliveryInfo(), OrderDeliveryVO.class);
			orderDeliveryVO.setSendId(MapUtil.getStr(dataMap, "send_id"));
			orderDeliveryVO.setSenderName(MapUtil.getStr(dataMap, "sender_name"));
			orderDeliveryVO.setSenderMobile(MapUtil.getStr(dataMap, "sender_mobile"));
			String status = MapUtil.getStr(dataMap, "status");
			if(Objects.equals(status, "appoint")){
				orderDeliveryVO.setAppointTime(DateUtil.now());
			}else if(Objects.equals(status, "receive")){
				orderDeliveryVO.setReceiveTime(DateUtil.now());
			}else if(Objects.equals(status, "station")){
				orderDeliveryVO.setStationTime(DateUtil.now());
			}else if(Objects.equals(status, "deliver")){
				orderDeliveryVO.setDeliverTime(DateUtil.now());
			}else if(Objects.equals(status, "arrived")){
				orderDeliveryVO.setArrivedTime(DateUtil.now());
			}else if(Objects.equals(status, "cancel")){
				orderDeliveryVO.setCancelTime(DateUtil.now());
			}

			orderService.updateById(Order.builder().id(order.getId()).logisticsDeliveryInfo(JsonUtil.toJson(orderDeliveryVO)).build());
			if("arrived".equals(status)){
				orderService.receiptOrder(order.getId());
			}
		}
		return R.status(true);
	}

}
